<template>
  <div class="page-container">
    <el-card class="card-container">
      <template #header>
        <div class="card-header">
          <span>标签管理</span>
          <el-button 
            v-if="tagCreateEnabled" 
            type="primary" 
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            新增标签
          </el-button>
          <el-tag 
            v-else 
            type="danger" 
            size="small"
            style="margin-left: 10px;"
          >
            标签创建功能已禁用
          </el-tag>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入标签名称"
          style="width: 200px"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      
      <!-- 标签列表 -->
      <el-table
        v-loading="loading"
        :data="tagList"
        stripe
        style="width: 100%"
        :row-class-name="getRowClassName"
        :key="tableKey"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="标签名称" min-width="150">
          <template #default="{ row }">
            <span :class="{ 'deleted-tag': row.deleted === 1 || row.deleted === '1' }">
              {{ row.name }}
              <el-tag v-if="row.deleted === 1 || row.deleted === '1'" type="info" size="small" style="margin-left: 8px;">
                已删除
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.deleted !== 1 && row.deleted !== '1'"
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              v-if="row.deleted !== 1 && row.deleted !== '1'"
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
            <el-button 
              v-if="row.deleted === 1 || row.deleted === '1'"
              type="success" 
              size="small" 
              @click="handleRestore(row)"
            >
              <el-icon><Refresh /></el-icon>
              恢复
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑标签对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入标签名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
import { 
  getTagList, 
  createTag, 
  updateTag, 
  deleteTag,
  restoreTag
} from '@/api/tag'
import { getConfigStatus } from '@/api/system'
import { emit, EVENT_TYPES } from '@/utils/eventBus'

// 响应式数据
const loading = ref(false)
const tagList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()
const tableKey = ref(0) // 用于强制重新渲染表格

// 配置状态
const tagCreateEnabled = ref(true)

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  id: null,
  name: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 50, message: '标签名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 获取标签列表
const fetchTagList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 只有当搜索关键词不为空时才添加搜索参数
    if (searchForm.name && searchForm.name.trim()) {
      params.name = searchForm.name.trim()
    }
    
    const response = await getTagList(params)
    
    if (response.code === 200) {
      // 强制更新数据，确保Vue能检测到变化
      const newList = response.data.records || []
      tagList.value = newList
      pagination.total = response.data.total || 0
      // 强制重新渲染表格
      tableKey.value++
    } else {
      ElMessage.error(response.message || '获取标签列表失败')
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('获取标签列表失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchTagList()
}

// 重置搜索
const handleReset = () => {
  searchForm.name = ''
  pagination.current = 1
  fetchTagList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchTagList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchTagList()
}

// 新增标签
const handleAdd = () => {
  dialogTitle.value = '新增标签'
  resetForm()
  dialogVisible.value = true
}

// 编辑标签
const handleEdit = (row) => {
  dialogTitle.value = '编辑标签'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除标签
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签"${row.name}"吗？\n删除后标签将变为灰色状态，可以随时恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteTag(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功，标签已变为灰色状态')
      fetchTagList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      
      // 优化错误信息显示
      if (error.message) {
        // 根据错误类型显示不同的提示
        if (error.message.includes('该标签下有文章')) {
          ElMessage({
            message: '无法删除：该标签下还有文章，请先移除或转移文章后再删除标签',
            type: 'warning',
            duration: 6000,
            showClose: true
          })
          // 可以在这里添加更详细的提示或跳转到文章管理页面
          console.log('建议：跳转到文章管理页面，将相关文章移除该标签')
        } else if (error.message.includes('标签名称已存在')) {
          ElMessage.warning('标签名称已存在，请使用其他名称')
        } else {
          ElMessage.error(error.message)
        }
      } else {
        ElMessage.error('删除标签失败，请检查网络连接')
      }
    }
  }
}

// 恢复标签
const handleRestore = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复标签"${row.name}"吗？`,
      '确认恢复',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const response = await restoreTag(row.id)
    
    if (response.code === 200) {
      ElMessage.success('恢复成功')
      fetchTagList()
    } else {
      ElMessage.error(response.message || '恢复失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复标签失败:', error)
      if (error.message) {
        ElMessage.error(error.message)
      } else {
        ElMessage.error('恢复标签失败，请检查网络连接')
      }
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    let response
    if (form.id) {
      // 编辑
      response = await updateTag(form.id, form)
    } else {
      // 新增
      response = await createTag(form)
    }
    
    if (response.code === 200) {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      await fetchTagList()
      
      // 发送事件通知其他页面刷新标签数据
      if (form.id) {
        emit(EVENT_TYPES.TAG_UPDATED, response.data)
      } else {
        emit(EVENT_TYPES.TAG_CREATED, response.data)
      }
      emit(EVENT_TYPES.REFRESH_TAGS)
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    
    // 优化错误信息显示
    if (error.message) {
      // 根据错误类型显示不同的提示
      if (error.message.includes('标签名称已存在')) {
        ElMessage({
          message: '标签名称已存在，请使用其他名称',
          type: 'warning',
          duration: 4000,
          showClose: true
        })
      } else if (error.message.includes('标签名称不能为空')) {
        ElMessage.warning('请输入标签名称')
      } else if (error.message.includes('标签名称不能超过50个字符')) {
        ElMessage.warning('标签名称不能超过50个字符')
      } else {
        ElMessage.error(error.message)
      }
    } else {
      ElMessage.error('操作失败，请检查网络连接')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.name = ''
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取行样式类名
const getRowClassName = ({ row }) => {
  if (row.deleted === 1 || row.deleted === '1') {
    return 'deleted-row'
  }
  return ''
}

// 页面加载时获取数据
// 检查配置状态
const checkConfigStatus = async () => {
  try {
    const response = await getConfigStatus()
    if (response.code === 200) {
      tagCreateEnabled.value = response.data.tagCreateEnabled
    }
  } catch (error) {
    console.error('获取配置状态失败:', error)
    ElMessage.error('获取配置状态失败')
  }
}

onMounted(() => {
  fetchTagList()
  checkConfigStatus()
})
</script>

<style lang="scss" scoped>
.page-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.card-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    color: #303133;
  }
  
  .search-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

// 已删除标签的样式
:deep(.deleted-row) {
  background-color: #f5f5f5 !important;
  color: #999 !important;
}

:deep(.deleted-row:hover) {
  background-color: #e8e8e8 !important;
}

.deleted-tag {
  color: #999;
  text-decoration: line-through;
}
</style>
